var async = require('async'),
	request = require('request'),
	config = require('./config'),
	Video = require('./proxy').Video,
	util = require('util'),
	low = require('lowdb');

var db = low('db.json');

var beg = config.beg;
var end = config.end;

var q = async.queue(function(task, cb) {
	task.run(task.beg, task.end, cb);
	cb();
}, 10);

var getOption = function(url) {
	return {
		method: 'GET',
		uri: url,
		gzip: true,
		headers: {
			'Cookie': config.vbaiduCookie,
			'User-Agent': config.vbaiduUserAgent
		}
	}
};

var parseIndex = function(body, beg, end) {
	var movieIndex = JSON.parse(body);
	if (beg != 0 && end != 20 && movieIndex.video_list.beg == 0 && movieIndex.video_list.end == 20) {
		return [];
	}

	var list = [];
	for (var i in movieIndex.video_list.videos) {
		var movie = movieIndex.video_list.videos[i];
		var workid = movie.works_id;
		list.push(util.format(config.movieDetailUrl, workid, config.vbaiduVersion));
	}

	beg = end;
	end = beg + config.step;

	//getIndex(beg,end);

	//var nextUri = util.format(config.movieIndexUrl, beg, end, config.vbaiduVersion);
	q.push({
		beg: beg,
		end: end,
		run: getIndex
	}, function(err) {});

	return list;
}

var saveToDb = function(movie) {
	//db('video').push(movie);
	Video.getVideoById(movie.id, function(err, v) {
		if (err) {
			console.log(err.message);
		} else {
			if (!v) {
				var video = movie;
				Video.newMovie(video.id,
					video.vtype,
					video.title,
					video.image,
					video.intro,
					video.rating,
					video.duration,
					video.pubtime,
					video.director,
					video.actor,
					video.area,
					video.type,
					video.tags,
					video.sites,
					function(err, m) {
						if (err) {
							console.log(err.message);
						}
					});
			}
		}
	});
}

var getDetail = function(url) {
	async.waterfall([
		function(cb) {
			var option = getOption(url);
			request(option, function(err, response, body) {
				if (err || response.statusCode != 200) {
					cb(err,url)
				} else {
					cb(null, body);
				}
			})
		},
		function(html, cb) {
			var video = JSON.parse(html);
			var object = {};
			object.id = video.id;
			object.title = video.title;
			object.vtype = 1;
			object.image = video.img_url;
			object.intro = video.intro;
			object.rating = video.rating;
			object.duration = video.duration;
			object.pubtime = video.pubtime;
			object.director = video.director;
			object.actor = video.actor;
			object.area = video.area;
			object.type = video.type;
			object.tags = video.tags;
			object.sites = video.sites.map(function(item) {
				return {
					name: item.site_name,
					url: item.site_url
				}
			});
			object.create_at = Date.now;

			cb(null, object)
		}
	], function(err, object) {
		if (err) {
			console.log(err,' ->',object);
		} else {
			saveToDb(object);
		}
	});
}

var getNextIndex = function(beg, end) {
	q.push({
		beg: beg,
		end: end,
		run: getIndex
	}, function(err) {});
}

var getIndex = function(beg, end) {
	var indexUrl = util.format(config.movieIndexUrl, beg, end, config.vbaiduVersion);
	var option = getOption(indexUrl);

	request(option, function(err, response, body) {
		if (err || response.statusCode != 200) {
			console.log('err: ', err);
			beg = end;
			end = beg + config.step;
			getNextIndex(beg, end);
		} else {
			var movieIndex = JSON.parse(body);
			if (beg != 0 && end != 20 && movieIndex.video_list.beg == 0 && movieIndex.video_list.end == 20) {
				console.log('end...');
				process.exit(1);
			} else {
				async.each(movieIndex.video_list.videos, function(item, callback) {
					var detailUrl = util.format(config.movieDetailUrl, item.works_id, config.vbaiduVersion);
					getDetail(detailUrl);
					callback(null, detailUrl);
				}, function(err,item) {
					if (err) {
						console.log(err.message,' ->',item);
					}
				})
				// for (var i in movieIndex.video_list.videos) {
				// 	var movie = movieIndex.video_list.videos[i];
				// 	var workid = movie.works_id;
				// 	var detailUrl = util.format(config.movieDetailUrl, workid, config.vbaiduVersion);
				// 	getDetail(detailUrl);
				// }
				beg = end;
				end = beg + config.step;
				getNextIndex(beg, end);
			}
		}
	});
}

//getIndex(beg,end);

q.push({
	beg: beg,
	end: end,
	run: getIndex
}, function(err) {});